package com.greenold.utils;

import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;

import java.util.List;
import java.util.Map;

/**
 * 🔧 流程工具类（静态方法版）
 * 说明：
 *  - 无需 @Autowired 注入
 *  - 通过 ProcessEngines.getDefaultProcessEngine() 获取引擎对象
 */
public class ActivityUtil {

    private static final ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    private static final RepositoryService repositoryService = processEngine.getRepositoryService();
    private static final RuntimeService runtimeService = processEngine.getRuntimeService();
    private static final TaskService taskService = processEngine.getTaskService();
    private static final HistoryService historyService = processEngine.getHistoryService();

    /**
     * 🚀 启动流程实例
     * @param processKey 流程定义key（bpmn中设置的id）
     * @param variables  流程变量
     * @return 流程实例对象
     */
    public static ProcessInstance startProcess(String processKey, Map<String, Object> variables) {
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(processKey, variables);
        System.out.println("✅ 流程启动成功，实例ID：" + instance.getId());
        return instance;
    }

    /**
     * 🔍 根据流程定义key查询当前激活任务
     */
    public static List<Task> getTasksByProcessKey(String processKey) {
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(processKey)
                .active()
                .list();
        tasks.forEach(task -> System.out.println("任务：" + task.getName() +
                " | ID：" + task.getId() +
                " | 处理人：" + task.getAssignee()));
        return tasks;
    }

    /**
     * 🔍 根据节点key查询任务
     */
    public static List<Task> getTasksByTaskKey(String processKey, String taskKey) {
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(processKey)
                .taskDefinitionKey(taskKey)
                .list();
        tasks.forEach(task -> System.out.println("任务：" + task.getName() +
                " | 节点：" + task.getTaskDefinitionKey() +
                " | ID：" + task.getId()));
        return tasks;
    }

    /**
     * ✅ 完成任务（带变量）
     */
    public static void completeTask(String id, Map<String, Object> variables) {
        Task task = taskService.createTaskQuery()
                .processInstanceId(id)
                .singleResult();

        if (task == null) {
            System.out.println("⚠️ 未找到对应任务，流程ID：" + id);
            return;
        }

        String taskId = task.getId();

        if (variables != null && !variables.isEmpty()) {
            taskService.complete(taskId, variables);
        } else {
            taskService.complete(taskId);
        }

        System.out.println("✅ 已完成任务，任务ID：" + taskId);
    }


    /**
     * 💬 添加审批意见
     * @param taskId 任务ID
     * @param processInstanceId 流程实例ID
     * @param comment 审批意见
     */
    public static void addComment(String taskId, String processInstanceId, String comment) {
        taskService.addComment(taskId, processInstanceId, comment);
        System.out.println("💬 添加审批意见成功：" + comment);
    }

    /**
     * 📋 查询流程实例下的所有审批意见
     */
    public static List<Comment> getCommentsByProcessInstance(String processInstanceId) {
        List<Comment> comments = taskService.getProcessInstanceComments(processInstanceId);
        System.out.println("📜 审批记录：");
        comments.forEach(c ->
                System.out.println(c.getUserId() + "：" + c.getFullMessage() + " | 时间：" + c.getTime()));
        return comments;
    }

    /**
     * 🧾 查询已完成任务（历史任务）
     */
    public static void getFinishedTasks(String processInstanceId) {
        historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .finished()
                .list()
                .forEach(t ->
                        System.out.println("✅ 已完成任务：" + t.getName() + " | 处理人：" + t.getAssignee()));
    }

    private ActivityUtil() {
        // 工具类禁止实例化
    }


    public static String getLatestAssignee(String processInstanceId, String activityId) {
        // ① 优先查当前正在执行的任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .taskDefinitionKey(activityId)
                .singleResult();

        if (task != null && task.getAssignee() != null) {
            return task.getAssignee();  // 当前正在执行的任务
        }

        // ② 否则查历史任务（取最新一条）
        HistoricTaskInstance latestHistoric = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskDefinitionKey(activityId)
                .orderByHistoricTaskInstanceStartTime().desc()
                .listPage(0, 1) // 只取最新一条
                .stream()
                .findFirst()
                .orElse(null);

        if (latestHistoric != null) {
            return latestHistoric.getAssignee();
        }

        return null; // 没查到任何记录
    }
    public static HistoricTaskInstance getHistoryTask(String processInstanceId, String activityId){
        return historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskDefinitionKey(activityId)
                .orderByHistoricTaskInstanceStartTime().desc()
                .listPage(0, 1) // 只取最新一条
                .stream()
                .findFirst()
                .orElse(null);
    }
    public static Task getTaskById(String processInstanceId){
        return taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    public static Comment getLatestCommentByActivity(String processInstanceId, String activityId) {
        // ① 查找该节点最新执行的任务（历史任务或正在执行）
        HistoricTaskInstance historicTask = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskDefinitionKey(activityId)
                .orderByHistoricTaskInstanceStartTime().desc()
                .listPage(0, 1)
                .stream()
                .findFirst()
                .orElse(null);

        if (historicTask == null) {
            System.out.println("⚠️ 未找到对应节点的任务记录，activityId=" + activityId);
            return null;
        }

        // ② 获取该任务的所有审批意见
        List<Comment> comments = taskService.getTaskComments(historicTask.getId());
        if (comments == null || comments.isEmpty()) {
            System.out.println("ℹ️ 节点 [" + activityId + "] 暂无审批意见。");
            return null;
        }

        // ③ 返回最新的一条（按时间倒序）
        comments.sort((c1, c2) -> c2.getTime().compareTo(c1.getTime()));
        Comment latestComment = comments.get(0);

        System.out.println("💬 最新审批意见：" + latestComment.getFullMessage() +
                " | 审批人：" + latestComment.getUserId() +
                " | 时间：" + latestComment.getTime());

        return latestComment;
    }
    public static List<HistoricTaskInstance> getHistoryTasks(String processInstanceId){
        return historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceStartTime().desc()
                .list();
    }
}
